#include "stdafx.h"
#include "ChessTrainer.h"

#include "ChessTree.h"
#include "ChessStatus.h"
#include "WinRate.h"

#include "../CommonTools/CommonStringFunction.h"
#include "../CommonTools/LogWriter.h"

#include <IStatus.h>
#include <IValue.h>

ChessTrainer::ChessTrainer(ExperientialSystem::DecisionTree* tree, ChessTree* chessTree):Trainer(tree),_chessTree(chessTree)
{

}

ChessTrainer::~ChessTrainer()
{

}

void ChessTrainer::RunEpoch()
{
	_chessTree->_onEpoch();
	if (this->GetTrainRound() != 0 && GetTrainRound() % 30 == 0)
	{
		int minPieceCount;
		int nonDefault = GetNonZeroValueCount(minPieceCount);
		LOG_FORMAT2("Total status: %d ;Non default values: %d", _tree->GetStatusSize(), nonDefault);
		LOG_FORMAT("Min non default depth: %d", minPieceCount);
	}
}

bool ChessTrainer::ShallEnd()
{
	return _chessTree->_checkEnd();
}

void ChessTrainer::OnStart()
{
	LOG("-------------Start-------------");
	_chessTree->_onStart();
}

int ChessTrainer::GetNonZeroValueCount(int& minPieces) const
{
	int res = 0;
	auto allStatus = _tree->GetAllStatus();
	minPieces = 10000000;
	for (auto status : allStatus)
	{
		auto children = status->GetAllNextStatus();
		bool hasNonDefaultValue = false;
		for (auto child : children)
		{
			ExperientialSystem::IValue *value;
			status->GetValue(child, value);
			WinRate* winrate = dynamic_cast<WinRate*>(value);
			if (winrate->GetWinRate() != DEFAULT_WINRATE)
			{
				++res;
				hasNonDefaultValue = true;
			}
		}

		if (hasNonDefaultValue)
		{
			//Update minPieces.
			ChessStatus* chessStatus = dynamic_cast<ChessStatus*>(status);
			int pieceCount = chessStatus->GetPieceCount();
			if (pieceCount < minPieces)
			{
				minPieces = pieceCount;
			}
		}
	}

	return res;
}
